//
//  PGPictureView.swift
//  PGWeibo
//
//  Created by Apple on 15/11/10.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit
import SDWebImage

/// 图片的间距
let statusCellPictureMargin: CGFloat = 8
/// 图片重用id
let statusPictrueCellreuseId = "statusPictrueCellreuseId"
class PGPictureView: UICollectionView, UICollectionViewDataSource {
    
    var viewModel: PGStatusViewModel? {
        didSet{
            sizeToFit()
            
            reloadData()
        }
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        return calcViewSize()
    }

    init() {
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = statusCellPictureMargin
        layout.minimumLineSpacing = statusCellPictureMargin
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        dataSource = self
        //注册cell
        registerClass(PGPictureViewCell.self, forCellWithReuseIdentifier: statusPictrueCellreuseId)
        backgroundColor = UIColor.whiteColor()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

//计算视图大小
extension PGPictureView {
    private func calcViewSize() -> CGSize {
        /// 每行的图片数量
        let rowCount: CGFloat = 3
        /// 布局
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        /// 图片整体的最大宽度
        let maxWidth = UIScreen.mainScreen().bounds.width - 2 * statusCellMargin
        /// 单个图片的宽度
        let itemWidth = (maxWidth - 2 * statusCellPictureMargin) / rowCount
        //布局 的itemsize
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        
        let count = viewModel?.thumbnailUrls?.count ?? 0
        
        if count == 0 {
            return CGSizeZero
        }
        
        if count == 1 {
            var size = CGSize(width: 150, height: 100)
            
            // 利用 SDWebImage 检查本地的缓存图像 - key 就是 url 的完整字符串
            // 问：SDWebImage 是如何设置缓存图片的文件名 完整 URL 字符串 -> `MD5`
            if let key = viewModel?.thumbnailUrls?.first?.absoluteString {
                let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
                size = image.size
            }
            
            // 过窄处理 - 针对长图
            size.width = size.width < 40 ? 40 : size.width
            // 过宽的图片
            if size.width > 300 {
                let w: CGFloat = 300
                let h = size.height * (w / size.width)
                
                size = CGSize(width: w, height: h)
            }
            
            layout.itemSize = size
            return size
        }
        
        if count == 4 {
            let w = itemWidth * 2 + statusCellPictureMargin
            return CGSize(width: w, height: w)
        }
        
        // 4> 其他图片 按照九宫格来显示
        // 计算出行数
        /**
        2 3
        5 6
        7 8 9
        */
        let row = CGFloat((count - 1) / Int(rowCount) + 1)
        let h = row * itemWidth + (row - 1) * statusCellPictureMargin
        let w = rowCount * itemWidth + (rowCount - 1) * statusCellPictureMargin
        return CGSize(width: w, height: h)
    }
}

// MARK: - dataSources
extension PGPictureView {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel?.thumbnailUrls?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(statusPictrueCellreuseId, forIndexPath: indexPath) as! PGPictureViewCell
        
        cell.imageURL = viewModel?.thumbnailUrls![indexPath.item]
        return cell
    }
}
// MARK: - 图片的cell
class PGPictureViewCell: UICollectionViewCell {
    var imageURL: NSURL? {
        didSet {
            iocnView.sd_setImageWithURL(imageURL, placeholderImage: nil, options: [SDWebImageOptions.RetryFailed,
                SDWebImageOptions.RefreshCached])
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private lazy var iocnView: UIImageView = {
        let v = UIImageView()
        v.contentMode = .ScaleAspectFill
//        v.layer.masksToBounds = true
        v.clipsToBounds = true
        return v
    }()
    
    private func setupUI() {
        contentView.addSubview(iocnView)
        iocnView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
    }
}

